package com.wzf.greattruth.zookeeper.lock;

import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wzf.greattruth.zookeeper.ZookeeperManager;
import com.wzf.greattruth.zookeeper.helper.ZookeeperHelper;

public class DistributedLock {
    private static final Logger LOGGER = LoggerFactory.getLogger(DistributedLock.class);
    private byte[] datas = null;
    private ZooKeeper zookeeper;

    public DistributedLock(ZooKeeper zookeeper) {
        super();
        this.zookeeper = zookeeper;
    }

    /**
     * 尝试获取锁标识
     * 
     * @param parentDir
     * @param nodeKey
     * @return
     */
    public boolean lock(String parentDir, String nodeKey) {
        if (StringUtils.isEmpty(parentDir) || StringUtils.isEmpty(nodeKey)) {
            // 参数不对，返回错误
            return false;
        }
        // 创建父级目录失败，直接返回
        boolean createResult = ZookeeperManager.getInstance().createDirIfNotExist(zookeeper, parentDir);
        if (!createResult) {
            return false;
        }

        // 在parentDir目录下创建临时节点，创建成功则认为上锁成功
        String path = ZookeeperHelper.getNodePath(parentDir, nodeKey);
        String nodePath = ZookeeperManager.getInstance().createNode(zookeeper, path, datas, CreateMode.EPHEMERAL);
        return StringUtils.isNoneBlank(nodePath);
    }

    /**
     * 删除锁标识
     * 
     * @param parentDir
     * @param nodeKey
     * @return
     */
    public boolean unlock(String parentDir, String nodeKey) {
        if (StringUtils.isEmpty(parentDir) || StringUtils.isEmpty(nodeKey)) {
            // 参数不对，返回错误
            return false;
        }
        // 删除节点
        String path = ZookeeperHelper.getNodePath(parentDir, nodeKey);
        return ZookeeperManager.getInstance().deleteNode(zookeeper, path);
    }
}
